package com.example.demo.config;

import com.example.demo.interceptors.JwtFilter;
import com.example.demo.security.LogoutSuccessHandlerService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.security.Security;

@Configuration
@Slf4j
public class securityConfig {
    @Resource
    private JwtFilter jwtFilter;

    @Resource
    private LogoutSuccessHandlerService logoutSuccessHandlerService;

    // 白名单路径
    public static final String[] WHITE_LIST = {
            "/login",
            "/register",
            "/api/public/**",
            // Swagger UI v3 (OpenAPI)
            "/v3/api-docs/**",
            "/swagger-ui/**",
            "/swagger-ui.html",
            "/webjars/**",
            "/swagger-resources/**"
    };

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();

    }

    /**
     * 配置过滤器SecurityFilterChain
     */

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                // 禁用 CSRF（跨站请求伪造）防护
                // 因为我们使用 JWT，不需要 CSRF
                .csrf(csrf -> csrf.disable())

                // 配置 Session 管理
                // STATELESS 表示不使用 Session，因为 JWT 是无状态的
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                ).authorizeHttpRequests(auth ->
                        auth
                                // 允许以下路径无需认证即可访问
                                .requestMatchers(
                                        WHITE_LIST
                                ).permitAll()
                                // 所有其他请求都需要认证
                                .anyRequest().authenticated()
                ).addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)

                    .logout(logout -> logout
                            .logoutSuccessHandler(logoutSuccessHandlerService)
                    )
                .build();

    }

    /**
     * 配置密码加密工具类
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        log.info("加载密码加密工具类");
        return new BCryptPasswordEncoder();
    }

}
